<template>
  <div class="cpt-comfy-workinfoitem shadow m-2 relative" @mouseenter="handleMouseEnter" @mouseleave="handleMouseLeave">

    <div class="pic" :style="customerStyle">

      <!-- <el-image style="width: 100%; height: 100%" :src="workInfo.poster" fit="cover" @click="handleImagePreview" /> -->
      <OptimizedImage :src="workInfo.poster" fit="cover" alt="作品图片" class="w-full"  @click="handleImagePreview"/>
      <!-- <el-image style="width: 100%; height: 100%" :src="workInfo.poster" :zoom-rate="1.2" :max-scale="7"
        :min-scale="0.2" :preview-src-list="[workInfo.poster]" :initial-index="4" fit="cover"
        @click="handleImagePreview" /> -->
    </div>
    <div class="cpt-comfy-workinfoitem-menu absolute bottom-0 left-0 w-full py-2 text-white"
      :class="[{ valid: showFavorMenu }]">
      <div class="menu-mask absolute w-full h-full bg-[#666] opacity-95 blur-[2px] rounded-lt-sm rounded-rt-sm z-10">
      </div>
      <div class="favormenucon p-t-4 w-full relative z-20">
        <div class="workinfoname text-white text-center m-b-7 ">
          {{ workInfo.name }}
        </div>
        <div class="flex justify-around items-center ">
          <div class="btn  cursor-pointer rounded-md px-2  py-1 bg-[#5AAEAC]  relative" @click="toggleFavorWork"
            v-if="isInteractiveInfoLoading">
            <el-icon>
              <ElIconLoading />
            </el-icon>
          </div>
          <div class="btn  cursor-pointer rounded-md px-2  py-1 bg-[#5AAEAC]  relative" @click="toggleFavorWork" v-else>
            <span v-if="interactiveInfo?.isFavor">
              取消点赞
            </span>
            <span v-else> 点赞 </span>
          </div>
          <div class="btn  cursor-pointer rounded-md px-2  py-1 bg-[#9DBFFB] relative" @click="downloadImage">下载</div>
          <div class="btn btn-copy cursor-pointer rounded-md px-2  py-1  relative" @click="goCopy"
            v-if="copyInfo?.type">
            <span v-if="copyInfo.type == 'sucai' || copyInfo.type == 'text2img'">
              复制提示词
            </span>
            <span v-if="copyInfo.type == 'app'">
              前往应用
            </span>
          </div>
        </div>
      </div>
    </div>
    <div class="pubcon absolute bottom-0 left-0 w-full p-t-4  px-2 p-b-1">
      <div class="line line-name w-full " :style="customerNameStyle">
        {{ workInfo.name }}
      </div>
      <div class=" flex justify-between">
        <div class="line line-author " v-if="showAuthor">
          <div class="avatar flex items-center">
            <PublicCptGoodsAvatar :size="16" :avatarUrl="workInfo?.appuser?.avatar"
              :goodsUrl="workInfo?.appuser?.goodsUrl">
            </PublicCptGoodsAvatar>
          </div>
          <div class="nickname">{{ workInfo?.appuser?.nickname }}</div>
          <div class="vip" :class="[`vip-${workInfo?.appuser?.VIPlevel}`]"></div>
        </div>
        <div class="line line-count " v-if="showCount">
          <div class="group m-r-2 viewCount">
            <span class="icon icon1"></span>
            <span class="text"> {{ workInfo?.favorsCount }} </span>
          </div>
          <div class="group viewCount">
            <span class="icon icon2"></span>
            <span class="text"> {{ workInfo?.downloadCount }} </span>
          </div>
        </div>


      </div>

    </div>

    <div class="btns  p-t-2 z-50 absolute bottom-0 left-0 w-full p-b-2 bg-white" v-if="showEditMenu">
      <!-- <div class="btn btn-edit" @click="clickEditWorkinfo">编辑</div> -->
      <div class="btn btn-delete" v-if="workInfo?.status == 11" @click="deleteWork">
        删除
      </div>
      <div class="btn btn-delete" v-if="workInfo?.status != 11" @click="cancelPubWork">
        取消发布
      </div>
    </div>

  </div>
  <el-image-viewer v-if="showViewer" :url-list="srcList" @close="closePreivew" close-on-press-escape>

  </el-image-viewer>
</template>
<script lang="ts" setup>

  import { BASE_URL, postAIAddWorkInfoDownload, postAICheckWorkInfoInteractive, postAICommentPage, postAICommentWork, postAIDeleteMyWorkInfo, postAIFavorWork, } from '../../service/yapi';
  import { defineEmits } from 'vue'
  const { token, } = useAuth();
  import { useAppStore } from "~/stores/app";
  import PublicCptGoodsAvatar from '~/components/public/CptGoodsAvatar.vue'
  import OptimizedImage from '~/components/OptimizedImage.vue'

  let app = useAppStore();
  let { togglePreviewModal } = app
  const props = defineProps({
    showEditMenu: {
      type: Boolean,
      default: true
    },
    showFavorMenu: {
      type: Boolean,
      default: false
    },
    valid: {
      type: Boolean,
      default: true
    },
    showAuthor: {
      type: Boolean,
      default: true
    },
    showCount: {
      type: Boolean,
      default: true
    },
    customerClick: {
      type: Boolean,
      default: false
    },
    workInfo: {
      type: Object,
      required: true,
      default: () => {
        return {
          "name": "",
          "intro": null,
          "isRecommend": 0,
          "isTop": 0,
          "type": 11,
          "payType": 0,
          "status": 11,
          "poster": "",
          "viewCount": 0,
          "favorsCount": 0,
          "reWriteCount": 0,
          "fileUrl": "",
          "badge": null,
          "activities": null,
          "baseFavorCount": 0,
          "downloadCount": 0,
          "modifyTime": null,
          "publishTime": null,
          "orderNum": 0,
          "showStyle": 1,
          "labels": null,
          "submissionTopic": null,
          "submissionTime": null,
          "weappQRcode": null,
          "copyInfo": null
        }
      }
    },
    width: {
      type: Number,
      default: 239
    },
    height: {
      type: Number,
      default: 120
    },
    posterId: {
      type: String,
      default: ''
    },
    showToggleIluPoster: {
      type: Boolean,
      default: false
    }
  })
  let { workInfo } = toRefs(props)
  let isIluPoster = computed(() => {
    console.log("%c Line:174 🍡 workInfo.value", "color:#b03734", workInfo.value);
    return workInfo.value.illustration == props.posterId
  })
  let copyInfo = computed(() => {
    try {
      let { copyInfo } = workInfo.value
      return JSON.parse(copyInfo)
    } catch (error) {
      return {}
    }

  })
  let showViewer = ref(false);
  let srcList = ref<any>([])
  let router = useRouter()
  let showCopyBtn = computed(() => {
    return copyInfo.value?.type
  })
  let goCopy = () => {
    let { type, workflowId } = copyInfo.value
    if (type) {
      if (type == 'sucai' || type == 'text2img') {
        navigator.clipboard.writeText(workInfo.value.name)
        ElMessage.success('复制成功')
      }
      if (type == 'app') {

        router.push({ path: `/apps/${workflowId}` })
      }
    }
    console.log('goCopy')
  }
  let customerStyle = computed(() => {
    let transHeight = props.height
    // 1 512X512 2 512X768 3 768X512 
    if (props.workInfo.showStyle == 1) {
      transHeight = props.width * 1
    }
    if (props.workInfo.showStyle == 2) {
      transHeight = props.width * 768 / 512
    }
    if (props.workInfo.showStyle == 3) {
      transHeight = props.width * 512 / 768
    }
    return {
      width: props.width + 'px',
      height: transHeight + 'px'
    }
  })
  let customerNameStyle = computed(() => {
    return {
      width: props.width + 'px'
    }
  })
  let emits = defineEmits(['clickUnPubWorkinfo', 'clickEditWorkinfo', 'deleteWorkinfoSuccess', 'downloadImage', 'clickImagePreview', "toggleIluPoster", 'customerClick'])

  let checkResult = ref<any>({
    status: {
      completed: false,
    },
    images: []

  })

  let downloadImage = () => {

    postAIAddWorkInfoDownload({ work: props.workInfo.id })
    props.workInfo.downloadCount = props.workInfo.downloadCount + 1
    emits('downloadImage', props.workInfo)
  }

  onMounted(() => {


  })
  let clickEditWorkinfo = () => {
    emits('clickEditWorkinfo', props.workInfo)
  }
  // 监听鼠标停留事件
  let mouseTimeout: NodeJS.Timeout | null = null;

  let isUserFoucs = ref(false)
  let { showFavorMenu } = toRefs(props)
  const handleMouseEnter = () => {
    if (!showFavorMenu.value) {
      return
    }
    if (mouseTimeout) {
      clearTimeout(mouseTimeout);
    }
    mouseTimeout = setTimeout(() => {
      // 鼠标停留超过500ms时执行的操作
      console.log('鼠标停留超过500ms');
      isUserFoucs.value = true
      checkInteractiveInfo()
    }, 500);
  };

  let isInteractiveInfoLoading = computed(() => {

    return interactiveInfo.value == null
  })

  const handleMouseLeave = () => {
    if (!showFavorMenu.value) {
      return
    }
    if (mouseTimeout) {
      clearTimeout(mouseTimeout);
      mouseTimeout = null;
      isUserFoucs.value = false
    }
  };
  let interactiveInfo = ref<any>(null)
  let checkInteractiveInfo = async () => {

    if (interactiveInfo.value) {
      return
    }
    let res: any = await postAICheckWorkInfoInteractive({ work: props.workInfo.id })
    if (res.code == 1000) {
      console.log("%c Line:189 🍊 res", "color:#7f2b82", res);
      interactiveInfo.value = res.data

    } else {

    }

  }
  let closePreivew = () => {
    showViewer.value = false;
  }
  let handleImagePreview = () => {

    if (props.customerClick) {
      emits('customerClick', props.workInfo)
      return
    }
    if (props.workInfo.inputFileUrl) {

      togglePreviewModal(props.workInfo)
    } else {
      showViewer.value = true
      srcList.value = [props.workInfo.fileUrl]
    }

    nextTick(() => {
      let wrapper = document.getElementsByClassName(
        "el-image-viewer__actions__inner"
      );
      let downImg = document.createElement("i");
      downImg.setAttribute("class", "el-icon el-icon-download");
      wrapper[0].appendChild(downImg);
      if (wrapper[0]) {
        wrapper[0].addEventListener('click', downloadImage)
      }

      // 新增逻辑 - 添加配图切换按钮
      if (props.showToggleIluPoster) {
        // 创建自定义按钮容器
        const buttonContainer = document.createElement("div");
        buttonContainer.classList.add("poster-selection-button");

        // 创建按钮
        const selectButton = document.createElement("button");
        selectButton.textContent = isIluPoster.value ? "取消配图" : "选为配图";
        selectButton.classList.add("toggle-ilu-button");


        // 根据当前状态设置样式
        if (isIluPoster.value) {
          selectButton.classList.add("is-active");
        }

        // 添加点击事件
        selectButton.addEventListener('click', (event) => {
          event.stopPropagation(); // 阻止事件冒泡
          toggleIluPoster();
        });

        // 将按钮添加到容器
        buttonContainer.appendChild(selectButton);

        // 将容器插入DOM
        const viewerContainer = document.querySelector(".el-image-viewer__actions__inner");
        if (viewerContainer) {
          viewerContainer.appendChild(buttonContainer);
        }
      }

    });

  }
  // 添加选择配图切换方法
  const toggleIluPoster = () => {
    if (!props.posterId) {
      ElMessage.warning('未找到诗词ID，无法设置配图');
      return;
    }

    // 触发事件，通知父组件处理逻辑
    emits('toggleIluPoster', {
      workInfo: props.workInfo,
      posterId: props.posterId,
      isSelected: isIluPoster.value
    });

    // 关闭查看器
    showViewer.value = false;
  }
  let toggleFavorWork = async () => {

    if (!token.value) {
      return ElMessage.warning('请先登录')
    }

    let res: any = await postAIFavorWork({
      work: Number(props.workInfo.id)
    })
    if (res.code == 1000) {
      if (res.data.id) {
        ElMessage.success("已点赞");
        props.workInfo.favorsCount = props.workInfo.favorsCount + 1;
      } else {
        ElMessage.warning("取消点赞了");
        props.workInfo.favorsCount = props.workInfo.favorsCount - 1;
      }
      interactiveInfo.value.isFavor = !interactiveInfo.value.isFavor
    } else {
      ElMessage.warning(res.message)
    }

  }
  let deleteWork = async () => {

    let res: any = await postAIDeleteMyWorkInfo({ id: props.workInfo.id })
    if (res.code == 1000) {
      ElMessage.success('取消成功，可以在未发布中选择作品重新发布')
      emits('deleteWorkinfoSuccess', { id: props.workInfo.id })
    } else {
      ElMessage.warning(res.message)
    }
  }
  let cancelPubWork = () => {
    ElMessageBox.confirm('确定取消发布吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteWork()
    }).catch(() => {
      ElMessage.info('已取消')
    });
  }
</script>
<style lang="scss">
  .cpt-comfy-workinfoitem {
    background: #F6F7FD;
    border-radius: 10px;
    overflow: hidden;

    .workinfoname {
      white-space: pre-wrap;
    }

    .cpt-comfy-workinfoitem-menu {
      font-size: 14px;
      display: none;
    }

    &:hover {
      .cpt-comfy-workinfoitem-menu.valid {
        display: block;
      }

      .btns {
        display: flex;
      }
    }

    .group {
      display: flex;
      align-items: center;
    }

    .line {
      display: flex;
      align-items: center;
    }

    .line.line-name {
      font-size: 12px;
      color: #fff;
      white-space: pre-wrap;


    }

    .line.line-count {
      justify-content: flex-start;
      // color: rgba(255, 255, 255, 0.65);
      color: #fff;

      .group {
        margin-top: 0;
        font-size: 12px;

        .icon {
          display: inline-block;
          width: 20px;
          height: 20px;
          cursor: pointer;
        }

        .icon1 {
          background: url("https://cdn.codinghou.cn/coding/pc-ai/icons/like-white.png") center center no-repeat;
          background-size: auto 12px;
        }

        .icon2 {
          background: url("https://cdn.codinghou.cn/coding/pc-ai/icons/download-white.png") center center no-repeat;
          background-size: auto 12px;
        }
      }
    }

    .line.line-author {
      cursor: pointer;
      justify-content: flex-start;


      overflow: hidden;

      .nickname {
        margin-left: 10px;

        color: #fff;
        font-size: 13px;
      }


    }


    .favormenucon {
      .btn-copy {
        background: rgba(244, 241, 97, 0.5);
      }

    }

    .btns {
      display: none;
      justify-content: space-between;

      &.btns-submission {
        display: block;
        text-align: center;

        .time {
          font-size: 16px;
          color: rgba(255, 255, 255, 0.65);
          margin-bottom: 20px;
        }
      }

      .btn {
        border-radius: 10px;
        font-size: 12px;


        @apply border-box text-center cursor-pointer px-2 py-1;
      }

      .btn-edit {
        @apply bg-purple-300;
      }

      .btn-delete {
        border: 1px solid;

        @apply text-purple-300 border-purple-300
      }

      .btn-submission {
        @apply bg-yellow text-purple-300;

      }
    }

    .pubcon {
      background: linear-gradient(180deg, rgba(77, 77, 77, 0) 0%, #333333 100%);
    }
  }
</style>